package sync

import kotlin.concurrent.thread

private var ticketNumber = 1000

/**
 * 不安全的买票
 * 线程不安全, 有负数的票
 */
fun main() {
    thread { buyTicket("志杰") }
    thread { buyTicket("小铭") }
    thread { buyTicket("我") }
}

@Synchronized
private fun buyTicket(name: String) {
    while (ticketNumber > 0) {
        Thread.sleep(5)
        println("$name 拿到第${ticketNumber--} 张票")
    }
}